import XmlStream from '../../../utils/xml-stream';
import BaseXform from '../base-xform';

import RelationshipXform from './relationship-xform';

class RelationshipsXform extends BaseXform {
    constructor() {
        super();

        this.map = {
            Relationship: new RelationshipXform(),
        };
    }

    render(xmlStream, model) {
        model = model || this._values;
        xmlStream.openXml(XmlStream.StdDocAttributes);
        xmlStream.openNode('Relationships', RelationshipsXform.RELATIONSHIPS_ATTRIBUTES);

        model.forEach(relationship => {
            this.map.Relationship.render(xmlStream, relationship);
        });

        xmlStream.closeNode();
    }

    parseXmlObject(xmlObject) {
        let hasValue = false
        xmlObject._elements.forEach((item) => {
            if (item._name === 'Relationships') {
                this.model = []
                item._elements.forEach((rel) => {
                    this.parser = this.map[rel._name];
                    if (this.parser) {
                        this.parser.parseXmlObject(rel);
                        this.model.push(this.parser.model);
                        this.parser = undefined;
                    }
                })
                hasValue = true;
            }
        });
        return hasValue;
    }

    parseOpen(node) {
        if (this.parser) {
            this.parser.parseOpen(node);
            return true;
        }
        switch (node.name) {
            case 'Relationships':
                this.model = [];
                return true;
            default:
                this.parser = this.map[node.name];
                if (this.parser) {
                    this.parser.parseOpen(node);
                    return true;
                }
                throw new Error(`Unexpected xml node in parseOpen: ${JSON.stringify(node)}`);
        }
    }

    parseText(text) {
        if (this.parser) {
            this.parser.parseText(text);
        }
    }

    parseClose(name) {
        if (this.parser) {
            if (!this.parser.parseClose(name)) {
                this.model.push(this.parser.model);
                this.parser = undefined;
            }
            return true;
        }
        switch (name) {
            case 'Relationships':
                return false;
            default:
                throw new Error(`Unexpected xml node in parseClose: ${name}`);
        }
    }
}

RelationshipsXform.RELATIONSHIPS_ATTRIBUTES = {
    xmlns: 'http://schemas.openxmlformats.org/package/2006/relationships',
};

export default RelationshipsXform;
